package org.hadoop.input.db;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class DBMR extends Configured implements Tool {
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        String url = "jdbc:mysql://127.0.0.1:3306/hadoop?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
        DBConfiguration.configureDB(conf, "com.mysql.cj.jdbc.Driver", url, "root", "123456");
        Path dest = new Path("D:/a/out003");
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(dest)) {
            fs.delete(dest, true);
        }
        Job job = Job.getInstance(conf, "db");
        job.setJarByClass(getClass());
        job.setMapperClass(DBMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(NullWritable.class);
        job.setReducerClass(DBReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        job.setInputFormatClass(DBInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        DBInputFormat.setInput(job, StudWritable.class, "stud", null, "id", "id", "name");
        FileOutputFormat.setOutputPath(job, dest);
        int code = job.waitForCompletion(true) ? 0 : 1;
        return code;
    }
    public static void main(String[] args) throws Exception {
        int run = ToolRunner.run(new DBMR(), args);
        System.exit(run);
    }
}